package com.eshop.web.intercepters;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.eshop.cache.SessionProvider;
import com.eshop.common.constant.CoreConstant;
import com.eshop.model.mongodb.manager.Manager;

public class ManagerIntercepter extends HandlerInterceptorAdapter {

	private static String redirect_login = "/manager/login";// 登录页面
	public String[] allowUrls;// 允许例外的url

	public void setAllowUrls(String[] allowUrls) {
		this.allowUrls = allowUrls;
	}

	@Autowired
	protected SessionProvider sessionProvider;

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 访问的路径
		String invokeUrl = request.getServletPath();
		// 先判断是否是允许例外的url
		if (null != allowUrls && allowUrls.length >= 1) {
			for (String url : allowUrls) {
				if (url.contains(invokeUrl)) {
					return true;
				}
			}
		}
		Manager user= (Manager) sessionProvider.getAttribute(request, CoreConstant.MANAGER_SESSION_KEY);
		if (user == null) {
				response.sendRedirect(redirect_login );// 未登录状态跳转到登录页面
			return false;
		}
		return true;
	}
}
